import React, { useEffect, useState } from 'react';
import {
  ProForm,
  ProFormDigit,
  ProFormText,
  ProFormRadio,
  ProFormTextArea,
  ProFormSelect,
  ProFormDatePicker,
  ProFormTimePicker,
  ProFormItem,
  ProFormDateTimePicker
} from '@ant-design/pro-components';
import { Form, message, Modal, Progress, Slider } from 'antd';
import { useIntl, FormattedMessage, useModel, useAccess, } from '@umijs/max';
import {getdeviceTypes, getdeviceNames ,getDeviceNumsByName} from '@/services/manage/asset';
import { values } from 'lodash';

export type AssetFormData = Record<string, unknown> & Partial<API.Manage.Asset>;

export type AssetFormProps = {
  onCancel: (flag?: boolean, formVals?: AssetFormData) => void;
  onSubmit: (values: AssetFormData) => Promise<void>;
  open: boolean;
  values: Partial<API.Manage.Asset>;
}

const AssetForm: React.FC<AssetFormProps> = (props) => {
  const {onCancel, onSubmit, open} = props;
  const [form] = Form.useForm();
  const [batteryLevel, setBatteryLevel] = useState(50);
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;
  
  const [deviceNames, setDeviceNames] = useState<string[]>([]);
  const [deviceNums, setDeviceNums] = useState<string[]>([]);
  const [deviceTypes, setDeviceTypes] = useState<string[]>([]);
  const access = useAccess();

  const allDeviceNames = async () =>{
      try{
        if(access.hasPerms('inspection:asset:allDeviceName')){
          const deviceNames = await getdeviceNames();
          const deviceNameList = Array.isArray(deviceNames?.rows) ? deviceNames.rows : [];
          setDeviceNames(deviceNameList);
        }
      }
      catch(error){
        message.error('获取设备名称失败:');
        setDeviceNames([]);
      }
    }

  const alldeviceTypes = async () =>{  
    try{
      if(access.hasPerms('inspection:deviceType:typeNames')){
        const deviceTypes = await getdeviceTypes();
        const deviceTypeList = Array.isArray(deviceTypes?.rows) ? deviceTypes.rows : [];
        setDeviceTypes(deviceTypeList)
      }
    } catch (error) {
      message.error('获取设备类型失败:');
      setDeviceTypes([]);
    }
  }


  useEffect(() => {
    console.log('props.values', props.values);    
    setBatteryLevel(props.values.batteryLevel ?? 0);
    form.resetFields();
    form.setFieldsValue({
      assetId: props.values.assetId,
      deviceName: props.values.deviceName,
      deviceNum: props.values.deviceNum,
      ipAddress: props.values.ipAddress,
      deviceType: props.values.deviceType,
      // batteryLevel: props.values.batteryLevel,
      isOnline: props.values.isOnline,
      networkStatus: props.values.networkStatus,
      lastOnline: props.values.lastOnline,
      remark: props.values.remark
    });
    allDeviceNames(); // 获取所有设备类型
    alldeviceTypes(); // 获取所有设备名称
  }, [form, props]);

  const handleFinish = async (values: Record<string, any>) => {
    const AssetFormData = {
      ...values,
      isOnline: Number(values.isOnline), // 将在线状态转换为数字
      networkStatus: Number(values.networkStatus), // 将网络状态转换为数字
      careateBy: currentUser?.nickName, // 获取当前用户的用户名;        
      updateBy: currentUser?.nickName , // 获取当前用户的用户名
      userId: Number(currentUser?.userId),
    }
    onSubmit(AssetFormData); // 提交表单数据
    console.log(AssetFormData);
  };

  return (
    <Modal
      width={640}
      title={props.values.assetId? '编辑资产':'添加资产'}
      forceRender
      open={props.open}
      onOk={()=>form.submit()} // 触发表单提交
      onCancel={()=>onCancel()} // 关闭模态框
    >
      <ProForm
        form={form}
        grid={true}
        layout="horizontal"
        submitter={false}
        onFinish={handleFinish} // 处理表单提交
        initialValues={{
          date: Date.now(),
          time: Date.now(),
        }}>
        <ProFormDigit
            name="assetId"
            label='资产编号'
            placeholder="请输入资产编号"
            disabled
            hidden={true}
            rules={[
              {
                required: false,
                message: "请输入资产编号！",
              },
            ]}
          />
        <ProFormText
          name="deviceName"
          label='设备名称'
          placeholder="请输入设备名称"
          rules={[
            {
              required: true,
              message: "请输入设备名称!",
            },
          ]}
        />       
        <ProFormText
          name="deviceNum"
          label='设备编号'
          placeholder="请输入设备编号"
          rules={[
            {
              required: true,
              message:"请输入设备编号!" ,
            },           
          ]}
        />
        <ProFormText
          name="ipAddress"
          label="IP地址"
          placeholder="请输入IP地址"
          rules={[
            {
              required: true,
              message: "请输入IP地址!",
            },
            {
              pattern: /^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}$/,
              message: '请输入有效的IPv4地址，例如：192.168.0.1',
            },
          ]}
        />            
        <ProFormSelect
          name="deviceType"
          label='设备类型'
          options={deviceTypes}
          placeholder="请选择设备类型"
          rules={[{ required: true, message: '请选择设备类型!' }]}
        />
        <ProFormRadio.Group
          options={[
            { label: '离线', value: 0 },
            { label: '在线', value: 1 },
          ]}
          name="isOnline"
          label='在线状态'
          placeholder="请输入在线状态"
          rules={[
            {
              required: true,
              message: "请输入在线状态！" ,
            },
          ]}
          fieldProps = {{
            defaultValue: 0
          }}
        /> 
        {/* <ProFormItem 
          name="batteryLevel"  // 添加 name 属性，使其成为表单的一部分
          label="设备电量" 
          style={{ width: 300 }} // 设置宽度
          rules={[  // 添加必填规则
            {
              required: true,
              message: "请设置设备电量！",
            },
          ]}
        >
          <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
            <Slider
              min={0}
              max={100}
              step={1}
              value={batteryLevel}
              onChange={(val) => {
                setBatteryLevel(val);
                // 更新表单的值
                form.setFieldValue('batteryLevel', val);
              }}
              style={{ flex: 1, marginRight: 16 }}
            />
            <span style={{ 
              minWidth: '40px', 
              textAlign: 'right',
              whiteSpace: 'nowrap' 
            }}>
              {batteryLevel}%
            </span>
          </div>
        </ProFormItem> */}
        <ProFormRadio.Group
          options={[
            { label: '异常', value: 0 },
            { label: '正常', value: 1 },
          ]}
          name="networkStatus"
          label='网络状态'
          placeholder="请输入网络状态"
          rules={[
            {
              required: true,
              message:"请输入网络状态！",
            },
          ]}
          fieldProps = {{
            defaultValue: 1
          }}
        /> 
        <ProFormDateTimePicker
          name="lastOnline"
          label="最后在线时间"
          fieldProps={{
            format: 'YYYY-MM-DD HH:mm:ss',  // 可自定义时间格式
            showTime: true,
          }}
          rules={[
            {
              required: true,
              message: "请选择最后在线时间！",
            },
          ]}
        /> 
        <ProFormTextArea
          name="remark"
          label='备注'
          placeholder="请输入备注信息"        
        />
      </ProForm>
    </Modal>
  );
};

export default AssetForm;